// pages/challenge/challenge.js
const rightMusicUrl = 'https://channel.kxqianbao.com/ok.mp3'//回答正确
const errorMusicUrl = 'https://channel.kxqianbao.com/fail.mp3'//回答错误
const countDownMusicUrl = 'https://channel.kxqianbao.com/timelock.mp3'//超时
const app = getApp()
const url = app.basicsUrl();
var times;
Page({
  data: {
    defaultImg: "../../images/answerGame/initial_icon.png",
    correctImg: "../../images/answerGame/correct_icon.png",
    errorImg: "../../images/answerGame/error_icon.png",
    num: 1,
    countDown: 10,
    version: "",
    list: "",
    questionType: 5,
    title: "",
    answerList: [],
    rightKey: "",
    titleNumber: 1,
    tapIndex: "0",
    showTheCorrectAnswer: false,
    mask: true,//控制蒙版
    scoreArr:[]
  },
  onLoad: function (options) {
    
  },
  onReady: function () {

  },
  onShow: function () {
    this.getLocation();
    this.countDown();
  },
  onHide: function () {
    wx.stopBackgroundAudio();
  },
  onUnload: function () {
    wx.stopBackgroundAudio();
    clearInterval(times)
  },//获取题目
  init() {
    var that = this;
    wx.request({
      url: url + 'questions',
      success: res => {
        if (res.data.code == 200) {
          var data = res.data.data;
          wx.setStorage({
            key: 'questionInfo',
            data: data,
          })
        }
      },
      fail: res => {
        wx.showModal({
          title: '提示',
          content: res.data.msg,
          showCancel: false
        })
      }
    })
  },//获取本地题目数据
  getLocation() {
    var that = this;
    wx.getStorage({
      key: 'questionInfo',
      success: res => {
        var data = res.data,
          version = data.version,
          list = data.questionList;
        that.setData({
          version: version,
          list: list
        })
        that.isUpdate(version);
        that.random(list)
      },
      fail: () => {
        that.init();
      }
    })
  },//本地数据是否需要更新
  isUpdate() {
    var that = this;
    var version = that.data.version;
    wx.request({
      url: url + 'questions/needUpdate',
      data: {
        version: version
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        if (res.data.code == 200) {
          if (res.data.data) {
            that.init();
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false
          })
        }
      },
      fail: res => {
        wx.showModal({
          title: '提示',
          content: res.data.msg,
          showCancel: false
        })
      }
    })
  },//随机题目
  random(list) {
    var that = this;
    var newArray = [];
    var answerList = [];
    var tempArray = [];//一个临时数组，用来存储已经随机到的题目，防止出现重复的题目
    var questionType = that.data.questionType;
    for (var i = 0; i < list.length; i++) {
      if (list[i]['questionType'] == questionType) {
        newArray.push(list[i])
      }
    }
    var len = newArray.length;
    var num = Math.floor(Math.random() * len + 1);
    tempArray.push(num);
    if (that.inArray(tempArray, num)) {
      // 在数组里
      var num = Math.floor(Math.random() * len + 1);
      var data = newArray[num];
      answerList.push(data.ans1)
      answerList.push(data.ans2)
      answerList.push(data.ans3)
    } else {
      // 不在数组里
      var data = newArray[num];
      answerList.push(data.ans1)
      answerList.push(data.ans2)
      answerList.push(data.ans3)
    }
    that.setData({
      title: data.question,//问题
      answerList: answerList,//问题选项列表
      rightKey: data.trueAns,//正确答案的索引
      showTheCorrectAnswer: false,
      mask: true
    })
  },//点击选项
  answerTap(e) {
    var that = this,
      rightKey = that.data.rightKey,
      list = that.data.list,
      titleNumber = that.data.titleNumber,
      idx = e.currentTarget.dataset.idx;
    that.setData({
      tapIndex: idx,
      mask: false
    })
    if (idx == rightKey) {
      console.log(idx, rightKey)
      clearInterval(times)
      that.setData({
        tapIndex: 0,
        countDown: 10,
        showTheCorrectAnswer: true
      })
      that.countDown();
      setTimeout(() => {
        that.random(list);
        that.setData({
          titleNumber: ++titleNumber,
        })
      }, 1000)
    }
  },//判断一个元素是否在数组中
  inArray: function (arr, obj) {
    var i = arr.length;
    while (i--) {
      if (arr[i] === obj) {
        return true;
      }
    }
    return false;
  },//倒计时
  countDown() {
    var that = this;
    var i = that.data.countDown;
    times = setInterval(function () {
      var k = --i;
      if (k == 3) {
        that.playMusic(countDownMusicUrl)
      }
      if (k == 0) {
        console.log(that.data.rightKey)
        clearInterval(times)
        that.setData({
          showTheCorrectAnswer: true,
          mask: false
        })
      }
      that.setData({
        countDown: k
      })
    }, 1000)
  },//再试一次
  tryAgain() {
    var that = this,
      list = that.data.list,
      num = that.data.num;
    clearInterval(times);
    wx.stopBackgroundAudio();
    that.setData({
      countDown: 10,
      titleNumber: 1,
      num: ++num,
      showTheCorrectAnswer: false,
      mask: true
    })
    that.countDown();
    that.random(list)
  },//放弃挑战
  giveUp() {
    wx.redirectTo({
      url: '../../pages/games/games?gameId=1&hongBaoHardType=1&hongBaoId=1'
    })
  },//播放背景音乐
  playMusic(musicUrl) {
    var backgroundAudioManager = wx.getBackgroundAudioManager()
    backgroundAudioManager.src = musicUrl // 设置了 src 之后会自动播放
  },//得分模式
  scoringModel(countDown) {
    var that = this,
      score, k,
      titleNumber = that.data.titleNumber;//第几题
    switch (countDown) {
      case 10:
        score = 100;
        break;
      case 9:
        score = 90;
        break;
      case 8:
        score = 80;
        break;
      case 7:
        score = 70;
        break;
      case 6:
        score = 60;
        break;
      case 5:
        score = 50;
        break;
      case 4:
        score = 40;
        break;
      default:
        score = 30;
    }
    //答到第五题的时候提示“最后一题！分数*2！”
    if (titleNumber == 5) {
      k = score * 2
    } else {
      k = score;
    }
    that.data.scoreArr.push(k)
  }
})